package com.boyicloud.exchangeconsole.controller

import com.boyicloud.exchangeconsole.commnon.AlertUtil
import com.boyicloud.exchangeconsole.commnon.HttpClient
import com.boyicloud.exchangeconsole.view.IndexView
import de.felixroske.jfxsupport.AbstractJavaFxApplicationSupport
import de.felixroske.jfxsupport.FXMLController
import de.felixroske.jfxsupport.GUIState
import javafx.fxml.FXML
import javafx.fxml.Initializable
import javafx.scene.control.Alert
import javafx.scene.control.PasswordField
import javafx.scene.control.TextField
import javafx.scene.layout.AnchorPane
import jfxtras.styles.jmetro.JMetro
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.springframework.beans.factory.annotation.Autowired
import java.net.URL
import java.util.*

@FXMLController
class LoginViewController : Initializable {

    @Autowired
    lateinit var httpClient: HttpClient

    @FXML
    lateinit var root: AnchorPane

    @FXML
    lateinit var username: TextField

    @FXML
    lateinit var password: PasswordField

    val scope = MainScope()

    fun onLogin() {
        scope.launch {
            if (username.text.isNotEmpty() && password.text.isNotEmpty()) {
                val result = withContext(Dispatchers.IO) {
                    httpClient.login(mutableMapOf("username" to username.text, "password" to password.text))
                }
                if (result) {
                    GUIState.getScene().window.hide()
                    AbstractJavaFxApplicationSupport.showView(IndexView::class.java)
                } else {
                    AlertUtil.show(Alert.AlertType.WARNING, "用户名或密码错误，请检查！")
                }
            } else {
                AlertUtil.show(Alert.AlertType.WARNING, "请输入用户名密码！")
            }
        }
    }

    override fun initialize(location: URL?, resources: ResourceBundle?) {
        val jMetro = JMetro()
        jMetro.parent = root
    }
}